import java.awt.Point;
import java.util.ArrayList;

import com.speljohan.rsbot.script.Calculations;
import com.speljohan.rsbot.script.Random;
import com.speljohan.rsbot.script.wrappers.RSObject;

public class LostAndFound extends Random {

	private static int[] APPENDAGES = { 8994, 8995, 8996, 8997 };

	@Override
	public boolean activateCondition() {
		if (!isLoggedIn()) {
			return false;
		}
		final RSObject append = findObject(LostAndFound.APPENDAGES);
		if (append != null) { // && tileOnScreen(append.getLocation())){
			return true;
		}
		return false;
	}

	public int clickObject(final RSObject obj, final String action) {
		for (int i = 0; i < 40; i++) {
			if (obj != null && tileOnScreen(obj.getLocation())) {
				final Point loc = Calculations.tileToScreen(obj.getLocation());
				final Point guess = new Point((int) random(loc.getX() - 30, loc
						.getX() + 30), (int) random(loc.getY() - 30,
						loc.getY() + 30));
				moveMouse(guess);
				if (menuContains(action)) {
					clickMouse(guess, false);
					atMenu(action);
				}
			}
		}
		return random(100, 200);
	}

	@Override
	public String getAuthor() {
		return "illusion & Drizzt1112";
	}

	@Override
	public String getName() {
		return "LostAndFound";
	}

	@Override
	public double getVersion() {
		return 1;
	}

	@Override
	public int loop() {
		final RSObject app = findObject(LostAndFound.APPENDAGES);
		if (app != null) {
			final RSObject guess = findObject(LostAndFound.APPENDAGES[random(0,
					3)]);
			if (guess != null) {
				if (tileOnScreen(guess.getLocation())) {
					return clickObject(guess, "Operate");
				} else {
					walkTileMM(guess.getLocation());
				}
			}
			return random(100, 200);
		}
		if (app == null) {
			log.info("Out of the Matrix.");
			return -1;
		}
		return random(100, 200);
	}

	public boolean menuContains(final String item) {
		while (getMenuItems().size() == 0) {
			wait(random(100, 200));
		}
		final ArrayList<String> list = getMenuItems();
		for (int a = 0; a < list.size(); a++) {
			if (list.get(a).toLowerCase().contains(item.toLowerCase())) {
				return true;
			}
		}
		return false;
	}
}